package com.whj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whj.domain.constants.SystemCharConstants;
import com.whj.domain.constants.SystemConstants;
import com.whj.domain.dto.AddArticleDto;
import com.whj.domain.entity.Article;
import com.whj.domain.entity.ArticleTag;
import com.whj.domain.entity.Category;
import com.whj.domain.enums.AppHttpCodeEnum;
import com.whj.domain.response.ResponseResult;
import com.whj.domain.vo.ArticleDetailVo;
import com.whj.domain.vo.HotArticleVo;
import com.whj.domain.vo.ArticleListVo;
import com.whj.domain.vo.PageVo;
import com.whj.exception.SystemException;
import com.whj.mapper.ArticleMapper;
import com.whj.mapper.ArticleTagMapper;
import com.whj.mapper.CategoryMapper;
import com.whj.mapper.TagMapper;
import com.whj.service.ArticleService;
import com.whj.service.ArticleTagService;
import com.whj.utils.BeanCopyUtils;
import com.whj.utils.RedisCache;
import com.whj.utils.SecurityUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Auther: wanghaijun
 * @Date: 2023/5/21 - 05 - 21 - 22:08 
 * @Description: com.whj.com.whj.service.impl
 */

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    /**
     * 查询热门文章
     *
     * @return 返回数组
     */
    @Override
    public ResponseResult<Article> hotArticleList() {

        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        // 必须是正式的文章
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        // 安装浏览量进行排序
        queryWrapper.orderByDesc(Article::getViewCount);
        // 最多查询十条信息
        Page<Article> page = new Page<>(1, 10);
        page(page, queryWrapper);
        List<Article> articles = page.getRecords();
        //bean 拷贝
/*        List<HotArticleVo> articleVos = new ArrayList<>();
        for (Article article : articles) {
            HotArticleVo vo = new HotArticleVo();
            BeanUtils.copyProperties(article,vo);
            articleVos.add(vo);
        }*/
        List<HotArticleVo> hotArticleVos = BeanCopyUtils.copyBeanList(articles, HotArticleVo.class);
        return ResponseResult.okResult(hotArticleVos);
    }

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public ResponseResult<ArticleListVo> articleList(Integer pageNum, Integer pageSize, Long categoryId) {
        // Long userId = SecurityUtils.getUserId();
        //条件查询
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //如果有 categoryId 就要查询
        queryWrapper.eq(Objects.nonNull(categoryId) && categoryId > 0, Article::getCategoryId, categoryId);
        // 状态是正式发布
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        // 查询当前用户的文章
        //queryWrapper.eq(Article::getCreateBy,null);
        // 对isTop进行降序
        queryWrapper.orderByAsc(Article::getIsTop);
        queryWrapper.orderByDesc(Article::getCreateTime);
        // 分页查询
        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page, queryWrapper);

        // 查询categoryName
        List<Article> articles = page.getRecords();
        for (Article article : articles) {
            Category category = categoryMapper.selectById(article.getCategoryId());
            if (!Objects.isNull(category)) {
                article.setCategoryName(category.getName());
            }
        }

        //封装vo
        List<ArticleListVo> articleListVos = BeanCopyUtils.copyBeanList(page.getRecords(), ArticleListVo.class);
        PageVo pageVo = new PageVo(articleListVos, page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult<ArticleDetailVo> getArticleDetail(Long id) {
        //根据id查询文章
        Article article = getById(id);
        // 从redis 中获取viewCount
        Integer viewCount = redisCache.getCacheMapValue(SystemCharConstants.ARTICLE_VIEW_COUNT, id.toString());
        article.setViewCount(viewCount.longValue());
        // 转换成VO
        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article, ArticleDetailVo.class);
        // 根据分类id查询分类名
        Long categoryId = articleDetailVo.getCategoryId();
        Category category = categoryMapper.selectById(categoryId);
        if (category != null) {
            articleDetailVo.setCategoryName(category.getName());
        }
        //封装响应返回
        return ResponseResult.okResult(articleDetailVo);
    }


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     * 更新redis浏览量的数据
     *
     * @param id 更新id
     * @return
     */
    @Override
    public ResponseResult updateViewCount(Long id) {
        Integer object = redisCache.getCacheMapValue(SystemCharConstants.ARTICLE_VIEW_COUNT, id.toString());
        Long incremented = redisCache.incrementCacheMapValue(SystemCharConstants.ARTICLE_VIEW_COUNT, id.toString(), 1);
        if (!Objects.isNull(object) && incremented.equals((long) object)) {
            Article article = new Article();
            article.setViewCount(incremented);
            article.setId(id);
            amqpTemplate.convertAndSend("myqueue", article);
        }
        return ResponseResult.okResult();
    }

    @Autowired
    private ArticleTagService articleTagService;

    @Override
    public ResponseResult add(AddArticleDto articleDto) {
        //添加 博客
        Article article = BeanCopyUtils.copyBean(articleDto, Article.class);
        if (Objects.isNull(article.getId())) {
            article.setCategoryId(9L);
        }
        save(article);
        List<ArticleTag> articleTags = articleDto.getTags().stream()
                .map(tagId -> new ArticleTag(article.getId(), tagId))
                .collect(Collectors.toList());
        //添加 博客和标签的关联
        articleTagService.saveBatch(articleTags);
        return ResponseResult.okResult();
    }

    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 更加标题和摘要模糊查询
     *
     * @param pageNum
     * @param pageSize
     * @param title
     * @param summary
     * @return
     */
    @Override
    public ResponseResult<PageVo> selectByTitleAndSummary(Integer pageNum, Integer pageSize, String title, String summary) {
        Long userId = SecurityUtils.getUserId();
        // 根据条件进行查询
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(title), Article::getTitle, title);
        queryWrapper.like(StringUtils.hasText(summary), Article::getSummary, summary);
        // 查询当前用户的文章
        queryWrapper.eq(Article::getCreateBy, userId);
        queryWrapper.select();
        // 分页
        Page<Article> page = new Page<>(pageNum, pageSize);
        page(page, queryWrapper);

        // 封装数据
        PageVo pageVo = new PageVo(page.getRecords(), page.getTotal());

        return ResponseResult.okResult(pageVo);
    }

    /**
     * 查询文章详细信息
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult<ArticleDetailVo> articleDetail(Long id) {
        // 查询文章详细
        Article article = articleMapper.selectById(id);
        // 查询标签
        List<Long> listTags = articleMapper.selectTagList(id);
        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article, ArticleDetailVo.class);
        articleDetailVo.setTags(listTags);
        return ResponseResult.okResult(articleDetailVo);
    }

    @Autowired
    private ArticleTagMapper articleTagMapper;

    @Autowired
    private ArticleService articleService;

    /**
     * 更新文章
     *
     * @param addArticleDto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult updateArticle(AddArticleDto addArticleDto) {

        //添加 博客
        Article article = BeanCopyUtils.copyBean(addArticleDto, Article.class);
        articleService.updateById(article);
        List<ArticleTag> articleTags = addArticleDto.getTags().stream()
                .distinct()
                .map(tagId -> new ArticleTag(article.getId(), tagId))
                .collect(Collectors.toList());

        //添加 博客和标签的关联
        LambdaQueryWrapper<ArticleTag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleTag::getArticleId, article.getId());
        articleTagMapper.delete(queryWrapper);
        articleTagService.saveBatch(articleTags);
        return ResponseResult.okResult();
    }

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public ResponseResult deleteArticle(List<String> id) {
        List<Long> collect = id.stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        articleMapper.deleteBatchIds(collect);
        return ResponseResult.okResult();
    }
}
